package org.lex.swing;

import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.SwingConstants;

public class IconSet implements Icon {
	// anchor
	public static final int TOP = SwingConstants.TOP;
	public static final int CENTER = SwingConstants.CENTER;
	public static final int BOTTOM = SwingConstants.BOTTOM;
	// alignment
	public static final int HORIZONTAL = SwingConstants.HORIZONTAL;
	public static final int VERTICAL = SwingConstants.VERTICAL;
	// public static final int
	// =======================================
	private static final int DEFUALT_GAP = 6;
	private static final int DEFAULT_ANCHOR = CENTER;
	private final Icon[] iconSet;
	private int width = 0;
	private int height = 0;
	private int anchor = DEFAULT_ANCHOR;
	private int gap = DEFUALT_GAP;

	public static void main(String[] args) {
		Swings.show(
				new JLabel(new IconSet(6, Swings.questionIcon(), Swings.informationIcon(), Swings.warningIcon(), Swings.errorIcon(), Swings
						.directoryIcon())), false);
	}

	public IconSet(Icon... icons) {
		this(DEFUALT_GAP, icons);
	}

	public IconSet(int gap, Icon... icons) {
		this(DEFAULT_ANCHOR, gap, icons);
	}

	public IconSet(int anchor, int gap, Icon... icons) {
		this.anchor = anchor;
		this.gap = gap;
		this.iconSet = new Icon[icons.length];
		for (int i = 0, n = icons.length, len = n - 1; i < n; i++) {
			Icon icon = icons[i];
			iconSet[i] = icon;
			int h = icon.getIconHeight();
			if (h > this.height)
				this.height = h;
			width += icon.getIconWidth();
			if (i < len)
				width += gap;
		}
	}

	public int getIconHeight() {
		return height;
	}

	public int getIconWidth() {
		return width;
	}

	public void paintIcon(Component c, Graphics g, final int x, final int y) {
		g.translate(x, y);
		if (null != c && c.isOpaque()) {
			g.setColor(c.getBackground());
			g.fillRect(0, 0, width, height);
		}
		for (int i = 0, n = iconSet.length, iconX = 0; i < n; i++) {
			Icon icon = iconSet[i];
			int iconY = 0;
			if (anchor == IconSet.TOP)
				iconY = 0;
			else if (anchor == IconSet.CENTER)
				// ���������icon������Ŀհ׿ռ�ĸ߶ȱ������һ������
				iconY = (this.height - icon.getIconHeight() + 1) / 2;
			else if (anchor == IconSet.BOTTOM)
				iconY = this.height - icon.getIconHeight();
			icon.paintIcon(c, g, iconX, iconY);
			iconX += icon.getIconWidth() + this.gap;
		}
		g.translate(-x, -y);
	}
}
